
from django.shortcuts import render,redirect
from app01 import models

from app01.utilss.pagination import Paginator

from app01.utilss.forms import PrettyModelForm





def pretty_list(request):
    """靓号管理"""
    # for i in range(300):
    #     models.Prettynum.objects.create(
    #         num = '1999'+str(i),
    #         price = 1000+i,
    #         level = 1,
    #         status = 1
    #     )
    # models.Prettynum.objects.filter(id = 12) 等于12
    # models.Prettynum.objects.filter(id_gt = 12) 大于12
    # models.Prettynum.objects.filter(id__lt = 12) 小于12
    # models.Prettynum.objects.filter(id__gte = 12) 大于等于12
    # models.Prettynum.objects.filter(id__lte = 12) 小于等于12
    # models.Prettynum.objects.filter(id__in = [1,2,3]) 批量查询
    # models.Prettynum.objects.filter(num__startswith="1999") 以1999开头
    # views.py

    """靓号管理"""


    search_keyword = request.GET.get('search', '')
    paginator = Paginator(request, models.Prettynum.objects.all().order_by("-level"), search_keyword,
                          search_field='num')
    queryset = paginator.get_paginated_queryset()
    page_str_list = paginator.get_page_control_html()
    if not queryset.exists():
        search_message = "未找到符合条件的靓号。"
    else:
        search_message = ""

    return render(request, 'pretty_list.html', {
        'queryset': queryset,
        'page_str_list': page_str_list,
        'page': paginator.page,
        'total_page_count': paginator.total_page_count,
        'search_message': search_message,
        'request': request,  # 传递 request 对象
    })


def pretty_add(request):
    """添加靓号"""
    if request.method == 'Get':
        form = PrettyModelForm()
        return render(request, 'pretty_add.html', {'form': form})
    form = PrettyModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect('/pretty/list/')
    else:
        return render(request, 'pretty_add.html', {'form': form})

def pretty_edit(request,nid):
    row_object = models.Prettynum.objects.filter(id=nid).first()
    if request.method == 'GET':
        form = PrettyModelForm(instance=row_object)
        return render(request, 'pretty_edit.html', {'form': form})
    form = PrettyModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/pretty/list/')
    else:
        return render(request, 'pretty_edit.html', {'form': form})

def pretty_delete(request):
    """删除靓号"""
    nid = request.GET.get('nid')
    models.Prettynum.objects.filter(id=nid).delete()
    return redirect('/pretty/list/')